<?php

namespace common\components\oss;

use Yii;
use yii\base\Component;
use OSS\OssClient;
use OSS\Core\OssException;

/**
 * Class Aliyunoss
 *
 * @author  Qianlin Zhuang <qianlin.zhuang@gmail.com>
 * @time    2018/11/13 14:03
 * @package common\components\oss
 */
class Aliyunoss extends Component
{
    public static $oss;
    public $bucket;

    public function __construct()
    {
        parent::__construct();
        $accessKeyId = env('OSS_ACCESS_KEY');               // 获取阿里云oss的accessKeyId
        $accessKeySecret = env('OSS_ACCESS_KEY_SECRET');    // 获取阿里云oss的accessKeySecret
        $endpoint = env('OSS_END_POINT');                   // 获取阿里云oss的endPoint
        $this->bucket = env('OSS_BUCKET');
        self::$oss = new OssClient($accessKeyId, $accessKeySecret, $endpoint);  //实例化OssClient对象
    }

    /**
     * 使用阿里云oss上传文件
     *
     * ```php
     * Yii::$app->aliyunoss->upload($file_url,$file_name)
     *
     * ```
     *
     * @param $object   保存到阿里云oss的文件名
     * @param $filepath 文件在本地的绝对路径
     * @return bool     上传是否成功
     */
    public function upload($object, $filepath)
    {
        $bucket = $this->bucket;  //获取阿里云oss的bucket

        $result = array();
        try {
            $getOssInfo = self::$oss->uploadFile($bucket, $object, $filepath);
            if (isset($getOssInfo['info']['url']) && $getOssInfo['info']['url']) {
                $result['url'] = $getOssInfo['info']['url'];
            } else {
                return false;
            }
        } catch (OssException $e) {

            return false;
        };
        $url = $result['url'];
        return $url;

    }


    /**
     * 删除指定文件
     * @param $object 被删除的文件名
     * @return bool   删除是否成功
     */
    public function delete($object)
    {
        $res = false;
        $bucket = env('OSS_BUCKET');    //获取阿里云oss的bucket
        if (self::$oss->deleteObject($bucket, $object)) {
            //调用deleteObject方法把服务器文件上传到阿里云oss
            $res = true;
        }
        return $res;
    }

}

?>
